package com.zhentao.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Excel导出工具类
 */
@Component
public class ExcelExportUtil {

    /**
     * 导出Excel到响应流
     */
    public static void exportToResponse(HttpServletResponse response, String fileName, 
                                      List<String> headers, List<List<Object>> dataList) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            
            // 处理文件名编码，避免中文乱码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".xlsx");
            
            // 创建Excel工作簿
            try (Workbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("数据");
                
                // 创建标题行样式
                CellStyle headerStyle = createHeaderStyle(workbook);
                
                // 创建标题行
                Row headerRow = sheet.createRow(0);
                for (int i = 0; i < headers.size(); i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(headers.get(i));
                    cell.setCellStyle(headerStyle);
                    sheet.setColumnWidth(i, 15 * 256); // 设置列宽
                }
                
                // 创建数据行
                for (int i = 0; i < dataList.size(); i++) {
                    Row dataRow = sheet.createRow(i + 1);
                    List<Object> rowData = dataList.get(i);
                    
                    for (int j = 0; j < rowData.size(); j++) {
                        Cell cell = dataRow.createCell(j);
                        Object value = rowData.get(j);
                        setCellValue(cell, value);
                    }
                }
                
                // 写入响应流
                workbook.write(response.getOutputStream());
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            // 如果Excel生成失败，返回错误信息
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 导出Excel到字节数组
     */
    public static byte[] exportToBytes(String sheetName, List<String> headers, 
                                     List<List<Object>> dataList) throws IOException {
        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            
            Sheet sheet = workbook.createSheet(sheetName);
            
            // 创建标题行样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers.get(i));
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 15 * 256); // 设置列宽
            }
            
            // 创建数据行
            for (int i = 0; i < dataList.size(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                List<Object> rowData = dataList.get(i);
                
                for (int j = 0; j < rowData.size(); j++) {
                    Cell cell = dataRow.createCell(j);
                    Object value = rowData.get(j);
                    setCellValue(cell, value);
                }
            }
            
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
    
    /**
     * 创建标题行样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }
    
    /**
     * 设置单元格值
     */
    private static void setCellValue(Cell cell, Object value) {
        try {
            if (value == null) {
                cell.setCellValue("");
            } else if (value instanceof String) {
                cell.setCellValue((String) value);
            } else if (value instanceof Number) {
                if (value instanceof BigDecimal) {
                    cell.setCellValue(((BigDecimal) value).doubleValue());
                } else {
                    cell.setCellValue(((Number) value).doubleValue());
                }
            } else if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cell.setCellValue(sdf.format((Date) value));
            } else if (value instanceof Boolean) {
                cell.setCellValue((Boolean) value);
            } else {
                cell.setCellValue(value.toString());
            }
        } catch (Exception e) {
            // 如果设置单元格值失败，设置为空字符串
            cell.setCellValue("");
        }
    }
}
